#include "HugePageAllocator.h"
#include <linux/mman.h>
#include <sys/mman.h>
#include <unistd.h>
#include <cstdlib>
#include <cstdio>


void *HugePageAllocator::allocate(size_t size)
{
    if (size == 0)
    {
        fprintf(stderr, "[HugePageAllocator] Invalid size: 0\n");
        return nullptr;
    }
    // void *ptr = mmap(nullptr, size,
    //                  PROT_READ | PROT_WRITE,
    //                  MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_HUGE_1GB,
    //                  -1, 0);
    // if (ptr == MAP_FAILED)
    // {
    //     perror("[HugePageAllocator] mmap failed");
    //     exit(EXIT_FAILURE);
    // }

    void *ptr = mmap(nullptr, size,
                     PROT_READ | PROT_WRITE,
                     MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB | MAP_HUGE_2MB,
                     -1, 0);
    if (ptr == MAP_FAILED)
    {
        perror("[HugePageAllocator] mmap failed");
        exit(EXIT_FAILURE);
    }    


    return ptr;
}

void HugePageAllocator::deallocate(void *ptr, size_t size)
{
    if (ptr == nullptr)
    {
        return;
    }
    if (munmap(ptr, size) != 0)
    {
        perror("[HugePageAllocator] munmap failed");
    }
}
